package com.sr.examination.main;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import com.sr.examination.R;
import com.sr.examination.home.HomeFragment;
import com.tl.commonlibrary.ui.BaseFragment;

/**
 * @author JongSung
 * @Description 主界内容模块中的主内容，包括：首页内容，个人中心内容，以ViewPager+fragment的方式呈现
 * @date 2017/6/6 0006.
 */
public class MainPageViewModel {
    private MainActivity activity;
    private BaseFragment[] fragments;
    private FragmentManager manager;

    public MainPageViewModel(MainActivity mainActivity) {
        this.activity = mainActivity;
        manager = activity.getSupportFragmentManager();
        fragments = new BaseFragment[Item.values().length];
    }

    /**
     * Activity被系统回收时恢复Page中的fragments
     *
     * @param savedInstanceState
     */
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            Item currentItem = null;
            int index = savedInstanceState.getInt(MainActivity.ITEM_INDEX_KEY, Item.HOME.getIndex());
            for (int i = 0; i < fragments.length; i++) {
                int tmpIndex = Item.values()[i].getIndex();
                fragments[i] = (BaseFragment) manager.findFragmentByTag(String.valueOf(tmpIndex));
                if (index == tmpIndex) {
                    currentItem = Item.values()[i];
                }
            }
            if (currentItem != null) {
                activity.setCurrentItem(currentItem);
            } else {
                activity.setCurrentItem(Item.HOME);
            }
        }
    }

    public void showFragment(Item item) {
        if (item == null || activity.getCurrentItem() == item) {
            return;
        }
        hideAll();
        FragmentTransaction transaction = manager.beginTransaction();
        if (fragments[item.getIndex()] == null) {
            switch (item) {
                case HOME://首页
                    fragments[item.getIndex()] = new HomeFragment();
                    break;
                default:
                    break;
            }
            transaction.add(R.id.containerLayout, fragments[item.getIndex()], String.valueOf(item.getIndex()));
        } else {
            transaction.show(fragments[item.getIndex()]);
        }
        transaction.commitAllowingStateLoss();
    }

    public BaseFragment getFragment(Item item) {
        if (item == null) {
            return null;
        }
        if (item.getIndex() < 0 || item.getIndex() >= fragments.length) {
            return null;
        }
        return fragments[item.getIndex()];
    }

    public void hideAll() {
        FragmentTransaction transaction = manager.beginTransaction();
        for (int i = 0; i < Item.values().length; i++) {
            if (fragments[i] != null) {
                transaction.hide(fragments[i]);
            }
        }
        transaction.commitAllowingStateLoss();
    }
}
